package cn.edu.pku.ss.lbs.blip;

import cn.edu.pku.ss.lbs.position.SignalRecord;
import cn.edu.pku.ss.lbs.position.SignalSource;
import com.blipsystems.blipnet.api.blipnode.BlipNodeHandle;
import com.blipsystems.blipnet.api.blipnode.InquiryData;
import com.blipsystems.blipnet.api.blipserver.BlipServerException;
import com.blipsystems.blipnet.api.bluetooth.BluetoothAddress;
import com.blipsystems.blipnet.api.event.InquiryEvent;
import com.blipsystems.blipnet.api.event.InquiryEventListener;

import java.util.HashMap;
import java.util.Map;

public class BlipSignalSource extends SignalSource implements InquiryEventListener {
    private Map<BluetoothAddress, String> stationIndex = new HashMap<BluetoothAddress, String>();

    public void addBlipNodeHandle(String station, BlipNodeHandle handle, InquiryData inquiryData) {
        try {
            BlipNodeLocker.Lock(handle);
            handle.getInquiryHandler().addEventListener(this);
            handle.getInquiryHandler().startInquiry(inquiryData);
            stationIndex.put(handle.getBlipNodeID(), station);
        } catch (BlipServerException e) {
            e.printStackTrace();
        }
    }

    public void handleInquiryEvent(InquiryEvent evt) {
        switch (evt.getEventID()) {
            case InquiryEvent.TERMINAL_DETECTED:
                String station = stationIndex.get(evt.getBlipNodeID());
                String terminal = evt.getTerminalID().getColonSeperatedUpperCaseString();
                int rssi = evt.getRssiResult();
                long time = System.currentTimeMillis();
                notifyProcessors(new SignalRecord(station, terminal, rssi, time));
                break;
            case InquiryEvent.INQUIRY_COMPLETE:
                break;
            case InquiryEvent.FRIENDLY_NAME_DETECTED:
                break;
            case InquiryEvent.NAME_LOOKUP_COMPLETE:
                break;
        }
    }
}